var Fiber = require('fibers');
var orm = require('./modules/orm.js');

var Role = orm.defineModel('role', {
    fields: {
        name: orm.fields.Char()
    }
});

var User = orm.defineModel('user', {
    fields: {
        name: orm.fields.Char(),
        sex: orm.fields.Integer(),
        role: orm.fields.Reference({
            target: 'role',
            type: 'n1'
        })
    }
});

var sessionFactory = new orm.SessionFactory({
        host: 'localhost',
        user: 'root',
        password: 'sakaimasamipass',
        database: 'hello'
});

var session = sessionFactory.createSession();

var fn = Fiber(function() {
    session.begin();

    function getOne() {
        var user = new User({
            sex: undefined
        });

        var foundModel = session.getOne(user, {
            recurisive: true
        });
        console.log(foundModel);
    }

    function get() {
        user = new User({
            sex: undefined
        });
        var foundModels = session.get(user, {
            recurisive: true
        });
        console.log(foundModels);
    }

    function getAll() {
        foundModels = session.getAll(User, {
            recurisive: true
        });
        console.log(foundModels);
    }

    function add() {
        var user = new User({
            name: '金柳颀',
            sex: 0,
            role: {
                id: 2
            }
        });
        session.add(user);
        console.log(user);
    }

    function remove() {
        var user = new User({
            id: 9
        });
        console.log(session.remove(user));
    }

    function save() {
        var user = new User({
            id: 8
        });

        var foundModel = session.getOne(user, {
            recurisive: true
        });

        if ( foundModel != null ) {
            foundModel.name = 'king';
            console.log(session.save(foundModel));
        }
    }
    //getOne();
    //get();
    //getAll();
    add();
    //remove();
    //save();

    session.end();
});

fn.run();
